from datetime import datetime, timedelta
import random
from app.database.postgre import Session
from app.database.models import AppLoginTimes
from itertools import islice


def generate_login_records(session: Session, app_id: int, num: int = 100_000):
    # 获取本月时间范围（从当月第一天 00:00 到最后一天 23:59:59）
    now = datetime.now()
    month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)

    # 计算本月最后一天
    if now.month == 12:
        month_end = now.replace(year=now.year + 1, month=1, day=1)
    else:
        month_end = now.replace(month=now.month + 1, day=1)
    month_end = month_end - timedelta(seconds=1)  # 找回到当月最后时刻

    # 生成随机时间参数
    total_seconds = int((month_end - month_start).total_seconds())
    time_offsets = (random.randint(0, total_seconds) for _ in range(num))

    # 批量生成记录（使用生成器优化内存）
    records = (
        AppLoginTimes(
            app_id=app_id,
            create_time=month_start + timedelta(seconds=offset)
        )
        for offset in time_offsets
    )

    # 批量提交（每次提交1万条避免内存峰值）
    batch_size = 10_000
    for i in range(0, num, batch_size):
        end = min(i + batch_size, num)
        chunk = list(islice(records, end - i))
        session.add_all(chunk)
        session.commit()
        session.expunge_all()  # 清除会话中的对象以释放内存
